#include "inc/zg291_pm1_0.h"
#include "ui_zg291_pm1_0.h"

ZG291_PM1_0::ZG291_PM1_0(QSerialPort *serialPort,QTimer *m_timer,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ZG291_PM1_0),
    serialPort(serialPort),
    m_timer(m_timer)
{
    ui->setupUi(this);
}

ZG291_PM1_0::~ZG291_PM1_0()
{
    delete ui;
}

void ZG291_PM1_0::on_pushButton_clicked() // 读取参数按钮
{
    // 停止定时器（如果有）
    if (m_timer && m_timer->isActive()) {
        m_timer->stop();
    }

    // 检查串口状态
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
//        if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第一条指令：读取0x26-0x2f寄存器 (10个寄存器) ****************/
    QByteArray request1;
    request1.append(static_cast<char>(0x00));     // 从机地址
    request1.append(static_cast<char>(0x03));     // 功能码
    request1.append(static_cast<char>(0x00));     // 起始地址高字节
    request1.append(static_cast<char>(0x26));     // 起始地址低字节 (0x1A)
    request1.append(static_cast<char>(0x00));     // 寄存器数高字节
    request1.append(static_cast<char>(0x0a));     // 寄存器数低字节 (10个寄存器)

    // 计算并附加CRC
    quint16 crc1 = calculateCRC(request1);
    request1.append(static_cast<char>(crc1 & 0xFF));
    request1.append(static_cast<char>((crc1 >> 8) & 0xFF));

    // 发送第一条指令
    if (serialPort->write(request1) == -1) {
        qDebug() << "Write failed (1):" << serialPort->errorString();
//        if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第一条响应
    QByteArray response1;
    if (serialPort->waitForReadyRead(1000)) {
        response1 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response1 += serialPort->readAll();
        }
    } else {
        qDebug() << "Read timeout (1)";
//        if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第二条指令：读取0x82-0x83寄存器 (2个寄存器) ****************/
    QByteArray request2;
    request2.append(static_cast<char>(0x00));     // 从机地址
    request2.append(static_cast<char>(0x03));     // 功能码
    request2.append(static_cast<char>(0x00));     // 起始地址高字节
    request2.append(static_cast<char>(0x82));     // 起始地址低字节 (0x82)
    request2.append(static_cast<char>(0x00));     // 寄存器数高字节
    request2.append(static_cast<char>(0x02));     // 寄存器数低字节 (2个寄存器)

    // 计算并附加CRC
    quint16 crc2 = calculateCRC(request2);
    request2.append(static_cast<char>(crc2 & 0xFF));
    request2.append(static_cast<char>((crc2 >> 8) & 0xFF));

    // 发送第二条指令
    if (serialPort->write(request2) == -1) {
        qDebug() << "Write failed (2):" << serialPort->errorString();
//        if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第二条响应
    QByteArray response2;
    if (serialPort->waitForReadyRead(1000)) {
        response2 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response2 += serialPort->readAll();
        }
    } else {
        qDebug() << "Read timeout (2)";
//        if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 解析响应数据并更新UI ****************/

    // 解析第一条响应 (0x26-0x2f) - 16个寄存器
    if (response1.size() >= 23) {  // 10寄存器×2 + 5字节头尾
        // 寄存器0x26: PM1.0报警上限
        quint16 pm1_0up = (static_cast<quint8>(response1[3]) << 8) | static_cast<quint8>(response1[4]);
        ui->pm1_0up->setText(QString::number(pm1_0up));

        // 寄存器0x27: PM1.0报警上限回差
        quint16 pm1_0updeff = (static_cast<quint8>(response1[5]) << 8) | static_cast<quint8>(response1[6]);
        ui->pm1_0updeff->setText(QString::number(pm1_0updeff));

        // 寄存器0x28: PM1.0报警上限继电器
        quint16 pm1_0relay = (static_cast<quint8>(response1[7]) << 8) | static_cast<quint8>(response1[8]);
        ui->pm1_0relay->setCurrentIndex(pm1_0relay);

        // 寄存器0x29: PM1.0报警下限
        quint16 pm1_0doen = (static_cast<quint8>(response1[9]) << 8) | static_cast<quint8>(response1[10]);
        ui->pm1_0doen->setText(QString::number(pm1_0doen));

        // 寄存器0x2a: PM1.0报警下限回差
        quint16 pm1_0downdeff = (static_cast<quint8>(response1[11]) << 8) | static_cast<quint8>(response1[12]);
        ui->pm1_0downdeff->setText(QString::number(pm1_0downdeff));

        // 寄存器0x2b: PM1.0报警下限继电器
        quint16 pm1_0dewnrelay = (static_cast<quint8>(response1[13]) << 8) | static_cast<quint8>(response1[14]);
        ui->pm1_0dewnrelay->setCurrentIndex(pm1_0dewnrelay);

        // 寄存器0x2c: PM1.0预警上限
        quint16 pm1_0upwarning = (static_cast<quint8>(response1[15]) << 8) | static_cast<quint8>(response1[16]);
        ui->pm1_0upwarning->setText(QString::number(pm1_0upwarning));

        // 寄存器0x2d: PM1.0预警上限开关
        quint16 pm1_0upwarning_en = (static_cast<quint8>(response1[17]) << 8) | static_cast<quint8>(response1[18]);
        ui->pm1_0upwarning_en->setCurrentIndex(pm1_0upwarning_en);

        // 寄存器0x2e: PM1.0预警下限
        quint16 pm1_0downwarning = (static_cast<quint8>(response1[19]) << 8) | static_cast<quint8>(response1[20]);
        ui->pm1_0downwarning->setText(QString::number(pm1_0downwarning));

        // 寄存器0x2f: PM1.0预警下限开关
        quint16 pm1_0downwarning_en = (static_cast<quint8>(response1[21]) << 8) | static_cast<quint8>(response1[22]);
        ui->pm1_0downwarning_en->setCurrentIndex(pm1_0downwarning_en);

    } else {
        qDebug() << "Invalid response1 length:" << response1.size();
    }

    // 解析第二条响应 (0x82-0x83) - 2个寄存器
    if (response2.size() >= 7) {  // 2寄存器×2 + 5字节头尾
        // 寄存器0x82: 可根据需要处理
        qint16 pm1_0K = (static_cast<quint8>(response2[3]) << 8) | static_cast<quint8>(response2[4]);
        ui->pm1_0K->setText(QString::number(pm1_0K/10.0,'f',1));
        // 寄存器0x83: 可根据需要处理
        quint16 pm1_0B = (static_cast<quint8>(response2[5]) << 8) | static_cast<quint8>(response2[6]);
        ui->pm1_0B->setText(QString::number(pm1_0B));
    } else {
        qDebug() << "Invalid response2 length:" << response2.size();
    }

    // 恢复定时器（如果有）
//    if (m_timer) m_timer->start(2000);
}

void ZG291_PM1_0::on_pushButton_2_clicked() // 设置参数按钮
{
    // 停止定时器（如果有）
    if (m_timer && m_timer->isActive()) {
        m_timer->stop();
    }

    // 检查串口状态
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
//        if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第一条指令：写入0x1A-0x29寄存器 (16个寄存器) ****************/
    QByteArray request1;
    request1.append(static_cast<char>(0x00));     // 从机地址
    request1.append(static_cast<char>(0x10));     // 功能码(写多个寄存器)
    request1.append(static_cast<char>(0x00));     // 起始地址高字节
    request1.append(static_cast<char>(0x26));     // 起始地址低字节 (0x1A)
    request1.append(static_cast<char>(0x00));     // 寄存器数高字节
    request1.append(static_cast<char>(0x0a));     // 寄存器数低字节 (16个寄存器)
    request1.append(static_cast<char>(0x14));     // 字节数 (10寄存器×2=20字节)

    // 添加寄存器值
    request1.append(static_cast<char>(ui->pm1_0up->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0up->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0updeff->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0updeff->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0relay->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->pm1_0relay->currentIndex() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0doen->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0doen->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0downdeff->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0downdeff->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0dewnrelay->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->pm1_0dewnrelay->currentIndex() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0upwarning->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0upwarning->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0upwarning_en->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->pm1_0upwarning_en->currentIndex() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0downwarning->text().toUShort() >> 8));
    request1.append(static_cast<char>(ui->pm1_0downwarning->text().toUShort() & 0xFF));

    request1.append(static_cast<char>(ui->pm1_0downwarning_en->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->pm1_0downwarning_en->currentIndex() & 0xFF));

    // 计算并附加CRC
    quint16 crc1 = calculateCRC(request1);
    request1.append(static_cast<char>(crc1 & 0xFF));
    request1.append(static_cast<char>((crc1 >> 8) & 0xFF));

    // 发送第一条指令
    if (serialPort->write(request1) == -1) {
        qDebug() << "Write failed (1):" << serialPort->errorString();
//        if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第一条响应
    QByteArray response1;
    if (serialPort->waitForReadyRead(1000)) {
        response1 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response1 += serialPort->readAll();
        }
    } else {
        qDebug() << "Write response timeout (1)";
//        if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第二条指令：写入0x82-0x83寄存器 (2个寄存器) ****************/
    QByteArray request2;
    request2.append(static_cast<char>(0x00));     // 从机地址
    request2.append(static_cast<char>(0x10));     // 功能码(写多个寄存器)
    request2.append(static_cast<char>(0x00));     // 起始地址高字节
    request2.append(static_cast<char>(0x82));     // 起始地址低字节 (0x1A)
    request2.append(static_cast<char>(0x00));     // 寄存器数高字节
    request2.append(static_cast<char>(0x02));     // 寄存器数低字节 (16个寄存器)
    request2.append(static_cast<char>(0x04));     // 字节数 (2寄存器×2=20字节)
    float pm1_0K_float = ui->pm1_0K->text().toFloat();
    short pm1_0K_int = static_cast<short>(pm1_0K_float * 10);

    request2.append(static_cast<char>(pm1_0K_int >> 8));
    request2.append(static_cast<char>(pm1_0K_int & 0xFF));

    request2.append(static_cast<char>(ui->pm1_0B->text().toUShort() >> 8));
    request2.append(static_cast<char>(ui->pm1_0B->text().toUShort() & 0xFF));
    quint16 crc2 = calculateCRC(request2);
    request2.append(static_cast<char>(crc2 & 0xFF));
    request2.append(static_cast<char>((crc2 >> 8) & 0xFF));
    // 发送第一条指令
    if (serialPort->write(request2) == -1) {
        qDebug() << "Write failed (1):" << serialPort->errorString();
//        if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第一条响应
    QByteArray response2;
    if (serialPort->waitForReadyRead(1000)) {
        response2 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response2 += serialPort->readAll();
        }
    } else {
        qDebug() << "Write response timeout (1)";
//        if (m_timer) m_timer->start(2000);
        return;
    }
    // 恢复定时器（如果有）
//    if (m_timer) m_timer->start(2000);

    qDebug() << "Parameters set successfully";
}
